package com.example.simpledata.slice;
import com.example.simpledata.ResourceTable;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.Text;
import ohos.data.DatabaseHelper;
import ohos.data.preferences.Preferences;

public class MainAbilitySlice extends AbilitySlice {
    @Override
    public void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        // 获取Text实例
        Text text = (Text) findComponentById(ResourceTable.Id_text_helloworld);
        // 创建数据库管理类
        DatabaseHelper databaseHelper = new DatabaseHelper(getContext());
//        // 直接将Preferences对应的存储文件删除
//        databaseHelper.deletePreferences("myPreferences");
//        // 仅仅将已经记载到内存的Preferences数据从内存中删除
//        databaseHelper.removePreferencesFromCache("myPreferences");
        // 获取Preferences实例
        Preferences preferences = databaseHelper.getPreferences("myPreferences");
        preferences.registerObserver(new Preferences.PreferencesObserver() {
            @Override
            public void onChange(Preferences preferences, String s) {
                // 参数s为发生更改的键值对的键
                text.setText(preferences.getString(s, "无昵称数据"));
            }
        });
        // 从获取Preferences实例中获取键值
        String name = preferences.getString("name", "无昵称数据");
        // 设置文本组件文案
        text.setText(name);
        // 存储数据
        preferences.putString("name","存储的昵称数据");
        // 进行文件刷新
        preferences.flushSync();


    }
}
